package com.zhinan.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhinan.common.SysEnum;
import com.zhinan.dao.SysUserMapper;
import com.zhinan.entity.SysUser;
import com.zhinan.exception.ZhiNanException;
import com.zhinan.service.SysUserService;
import com.zhinan.utils.SaltUtils;
import com.zhinan.vo.UserLoginVo;
import com.zhinan.vo.UserRegVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description: TuTu_WorkManager
 * @Author: ZhiNan
 * @Date: 2023-04-10 14:50
 * @Version: 1.0
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;


    /**
     * 添加用户信息
     */

    public int addUser(UserRegVo userRegVo) {
        log.info("add user info: {}", userRegVo);
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUserName, userRegVo.getUserNum());
        SysUser selectOne = sysUserMapper.selectOne(lambdaQueryWrapper);
        if (!ObjectUtil.isEmpty(selectOne)) {
            throw new ZhiNanException(SysEnum.ErrorMsg.USER_EXIST.getCode(), SysEnum.ErrorMsg.USER_EXIST.getName());
        }

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userRegVo, sysUser);
        if (StrUtil.isBlank(sysUser.getUserName())) {
            sysUser.setUserName("用户_" + RandomUtil.randomInt(10000, 99999));  //生成默认的用户名
        }
        //设置部门相关信息
        sysUser.setDepNum(SysEnum.DepartMentInfo.DEFAULT_DEPART.getCode());
        sysUser.setDepName(SysEnum.DepartMentInfo.DEFAULT_DEPART.getName());
        //生成随机盐
        String salt = SaltUtils.getSalt(8);
        sysUser.setSalt(salt);
        //对明文密码进行MD5+salt+hash散列
        Md5Hash md5Hash = new Md5Hash(sysUser.getUserPwd(), salt, 1024);
        sysUser.setUserPwd(md5Hash.toHex());
        return sysUserMapper.insert(sysUser);
    }


    /**
     * 用户登录
     */
    public void login(UserLoginVo userLoginVo) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userLoginVo, sysUser);
        try {
            UsernamePasswordToken passwordToken = new UsernamePasswordToken(sysUser.getUserNum(), sysUser.getUserPwd(), userLoginVo.isRememberMe());
            Subject subject = SecurityUtils.getSubject();
            subject.login(passwordToken);
        } catch (UnknownAccountException e) {
            log.error("账号不存在", e);
            e.printStackTrace();
            throw new ZhiNanException(SysEnum.ErrorMsg.USER_NOT_EXIST.getCode(), SysEnum.ErrorMsg.USER_NOT_EXIST.getName());
        } catch (IncorrectCredentialsException e) {
            log.error("密码错误", e);
            throw new ZhiNanException(SysEnum.ErrorMsg.WRONG_PASSWORD.getCode(), SysEnum.ErrorMsg.WRONG_PASSWORD.getName());
        } catch (ExcessiveAttemptsException e) {
            log.error("密码错误次数过多", e);
            e.printStackTrace();
            throw new ZhiNanException(SysEnum.ErrorMsg.SYSTEM_ERROR.getCode(), SysEnum.ErrorMsg.SYSTEM_ERROR.getName());
        } catch (AuthenticationException e) {
            throw new ZhiNanException(SysEnum.ErrorMsg.SYSTEM_ERROR.getCode(), SysEnum.ErrorMsg.SYSTEM_ERROR.getName());
        }
    }
}
